<template>
  <view>
  
    <!-- 考勤统计部分 -->
    <view class="statistics-box">
      <view class="head">
        <image src="/static/images/192.png" mode="" style="width: 40rpx; height: 40rpx;"></image>
        <view class="head-text">{{nowMonth}}月份考勤统计</view>
      </view>
      <view class="time-box">
        <view class="time-left">
          <view class="workTime-left">{{validWork}}</view>
          <view class="" style="color: #999;">有效考勤</view>
        </view>
        <view class="time-left">
          <view class="workTime-left">{{invalidWork}}</view>
          <view class="" style="color: #999;">无效考勤</view>
        </view>
        <view class="time-left">
          <view class="workTime-left">{{nullWrok}}</view>
          <view class="" style="color: #999;">无考勤</view>
        </view>
        <view class="time-left">
          <view class="workTime-left">{{totalWorkTime}}<text style="font-size: 30rpx;">H</text></view>
          <view class="" style="color: #999;">累计时长</view>
        </view>
      </view>
    </view>
    
    <!-- 考勤详情部分 -->
    <view class="statistics-detail">
      <view class="head">
        <image src="/static/images/192.png" mode="" style="width: 40rpx; height: 40rpx;"></image>
        <view class="head-text">考勤详情</view>
      </view>
      
      <view class="calendar-wrapper">
          
      		<view class="header" v-if="headerBar">
      			<!-- <view class="pre" @click="changeMonth('pre')">上个月</view> -->
      			<view>{{y+'年'+formatNum(m)+'月'}}</view>
      			<!-- <view class="next" @click="changeMonth('next')">下个月</view> -->
      		</view>
          
      		<view class="week">
      			<view class="week-day" v-for="(item, index) in weekDay" :key="index">{{ item }}</view>
      		</view>
          
      		<view :class="{ hide: !monthOpen }" class="content" :style="{ height: height }">
      			<view :style="{ top: positionTop + 'rpx' }" class="days">
      				<view class="item" v-for="(item, index) in dates" :key="index">
      					<view class="day" @click="selectOne(item, $event)" :class="{
                                  choose: choose == `${item.year}-${item.month}-${item.date}`&&item.isCurM,
      				                    isMarkDay:isMarkDay(item.year, item.month, item.date),
                                  nolm: !item.isCurM,
                                  today: isToday(item.year, item.month, item.date),
                                  isWorkDay: isWorkDay(item.year, item.month, item.date),
                                  statusRed: item.status === 0,
                                  statusYellow: item.status === 1,
                                  statusGreen: item.status === 2,
                              }" >
      						{{ Number(item.date) }}
      					</view>
      					<!-- <view class="markDay" v-if="isMarkDay(item.year, item.month, item.date)&&item.isCurM"></view> -->
      					<!-- <view class="today-text" v-if="isToday(item.year, item.month, item.date)">今</view> -->
      				</view>
      			</view>
      		</view>
      <!-- 		<image style="width: 150rpx;" :src="require('../static/images/manager/calendar.png')" mode="scaleToFill" v-if="collapsible"
      			@click="toggle" class="weektoggle" :class="{ down: monthOpen }"></image> -->
      		<image style="width: 150rpx;" src="/static/images/向上.png" mode="heightFix" v-if="collapsible"
      			@click="toggle" class="weektoggle" :class="{ down: monthOpen }"></image>
            
      		<u-toast ref="uToast" />
      	</view>
      
      

    </view>
    
    <view class="calendar-tip">
      <view class="red-style" style="margin-left: 0rpx; margin-right: 10rpx;"></view>
      <view class="">全天考勤正常</view>
      <view class="red-bule" style="margin-left: 20rpx; margin-right: 10rpx;"></view>
      <view class="">异常: 出勤不足2小时</view>
    </view>
    
    <view class="statistics-box">
      <view class="title-head">
        <view class="" style="font-weight: 500;">统计</view>
      </view>
      <view class="time-box">
        <view class="time-left">
          <view class="workTime-left">{{dayWorkTime}}<text style="font-size: 30rpx;">H</text></view>
          <view class="" style="color: #999;">工作时长</view>
        </view>
        <view class="time-left">
          <view class="workTime-left">{{addDayWorkTime}}<text style="font-size: 30rpx;">H</text></view>
          <view class="" style="color: #999;">工作时长</view>
        </view>
      </view>
    </view>
    
    <view class="clockin-list" v-show="clockinList.length != 0">
      <view class="clockin-item" v-for="(item,index) in clockinList">
        <view class="item-head" style="padding-top: 30rpx;">
          <view :class=" item.status === 0 ? 'error' : (item.status === 1 ? 'warn' : '') " style="width: 20rpx; height: 20rpx; border-radius: 50%; background-color: #055dfe; margin-right: 20rpx;"></view>
          <view class="" style="color: #999;">{{item.workStatus == 0 ? '上班打卡' : '下班打卡'}}</view>
          <view class="item-head-status" :class=" item.status === 0 ? 'errornotback' : (item.status === 1 ? 'warnnotback' : '') " style="margin-left: 200rpx;">
            <text>{{item.status == 0 ? '无记录': '正常'}}</text>
          </view>
        </view>
        <view class="item-middle">
          <view class="item-middle-row">
            <text class="iconfont icon-clock"></text>
            <text style="padding-left: 30rpx;">{{item.time}}</text>
          </view>
          <view class="item-middle-row">
            <text class="iconfont icon-gps"></text>
            <text style="padding-left: 30rpx;">{{item.address}}</text>
          </view>
          <view class="item-middle-row">
            <text class="iconfont icon-fujian"></text>
            <text style="padding-left: 30rpx;">{{item.part}}</text>
          </view>
        </view>
        <view class="item-img" @click="clickImage(item.image)">
          <image :src="item.image" mode=""></image>
        </view>
      </view>
    </view>
    
    <view class="my-butbox" v-if="idCode.length == 0 && isShowButton">
      <button class="my-but" type="primary" @click="gotoConfirm">确认</button>
    </view>
  
  </view>
</template>

<script>
  import '@/static/common/iconfont.css'
  export default {
    props: {
    	// 星期几为第一天(0为星期日)
    	weekstart: {
    		type: Number,
    		default: 0
    	},
    	// 标记的日期
    	// markDays: {
    	// 	type: Array,
    	// 	// default: () => {
    	// 	// 	return ["2023-09-01", "2023-09-03", "2023-09-13"]; //例如["2023-05-01", "2023-05-03", "2023-04-13"]
    	// 	// }
     //    default: () => []
    	// },
    	//是否展示月份切换按钮
    	headerBar: {
    		type: Boolean,
    		default: true
    	},
    	// 是否展开
    	open: {
    		type: Boolean,
    		default: true
    	},
    	//是否可收缩
    	collapsible: {
    		type: Boolean,
    		default: true
    	},
    	//未来日期是否不可点击
    	disabledAfter: {
    		type: Boolean,
    		default: true
    	}
    },
    computed:{
      // 顶部星期栏
      weekDay() {
      	return this.weektext.slice(this.weekstart).concat(this.weektext.slice(0, this.weekstart));
      },
      height() {
      	return (this.dates.length / 7) * 80 + 'rpx';
      }
      
    },
    watch:{
      timeAndsta(newval,oldval){
        console.log('数据加载完成');
        this.dates = this.monthDay(this.y, this.m);
        this.$nextTick(() => {
          // this.$refs.calendar.$forceUpdate();
        })
      },
      immediate: true
    },
    data() {
      return {
        idCode: null, //指定查询的身份证号
        datetime: '',
        isShowButton: true,
        weektext: ['日', '一', '二', '三', '四', '五', '六'],
        y: new Date().getFullYear(), // 年
        m: new Date().getMonth() + 1, // 月
        dates: [], // 当前月的日期数据
        positionTop: 0,
        monthOpen: true,
        choose: '',
        markDays: [],
        
        
        timeAndsta: [], //考勤的日期和状态 用来在日历上展示
        attendanceList: [], //全查考勤列表
        nowMonth: 9, // 当前的月份
        nowYear: 2023, // 通过多少年份点击进来的 在onload会改变
        titleindex: 0,
        pageNum:1,
        pageSize: 31, //每次只查一个月 一次全查
        days: 31,
        statisticsIndex: 0,
        dayWorkTime: 0, //工作时长
        addDayWorkTime: 0, //加班时长
        totalWorkTime: 0 ,//累计时长
        validWork: 0 ,//有效考勤
        invalidWork: 0 ,//无效考勤
        nullWrok: 0 ,//无考勤
        clockinList: { // 打卡对象
          status: 0 ,// 0正常 1黄色警告 2红色无记录
          workStatus: 0, // 0上班打卡 1下班打卡
          time: '07:59:34',
          address: '九江市濂溪区九江职业大学',
          part: '考勤附件',
          image: '/static/images/avatar.jpg'
        }
      };
    },
    methods: {
      
      clickImage(url){
        console.log('点击了图片');
        uni.previewImage({
          current: 0,
          urls: [url]
        })
      },
      
      // 跳转到人脸验证页面
      gotoConfirm(){
        uni.redirectTo({
           url: './jobFace?year=' + this.nowYear +'&month=' + this.nowMonth
        })
      },
        
      // 将前端返回的工作时长 格式化为number 比如 8小时56分钟52秒
      convertTimeToHours(timeString) {
        if(timeString == null || timeString == 0){
          console.log('将后端返回的工作时长 格式化为number 接受到了 null');
          return 0
        }
        // 使用正则表达式匹配可能存在的小时、分钟和秒部分
        const regex = /(\d+)时?(\d*)分?(\d*)秒?/;
        const matches = timeString.match(regex);
      
        if (matches) {
          const hours = parseInt(matches[1], 10);
          const minutes = parseInt(matches[2], 10) || 0; // 默认为0
          const seconds = parseInt(matches[3], 10) || 0; // 默认为0
      
          // 将分钟和秒数转换为小时的小数
          const hoursDecimal = hours + minutes / 60 + seconds / 3600;
      
          // 限制小数点后不超过两位
          const roundedHours = parseFloat(hoursDecimal.toFixed(2));
          
          return roundedHours;
        } else {
          // 如果字符串格式不正确，返回null或者其他错误处理方式
          return null;
        }
      },
      
      //点击上一个月点击下一个月
      clickMonth(e){
        // 每次切换月份的时候 先显示当天的数据 给当月数据一点加载的时间
        this.statisticsIndex = 0
        // 月份补0 统一格式
        e.m = e.m <= 9 ? '0' + e.m : e.m
        if(e.m == 13){
          e.m = '01'
          e.y += 1
        }
        if(e.m == 0){
          e.m = 12
          e.y -= 1
        }
        
        if(this.idCode != null){
          this.getattendanceList(e.y + '-' + e.m + '-' + '01', this.idCode)
        }else{
          this.getattendanceList(e.y + '-' + e.m + '-' + '01')
        }
        this.days = this.getDaysInMonth(e.y + '-' + e.m + '-' + '01')
      },
      
      // 在日历上选中日期 打卡修改
      onclickTime(e){
        // console.log('选中日期',e);
        if(e.date == null){
          console.log('在日历上选中日期 打卡修改 接受到null');
          return 
        }
        let flg = true
        let allClockinList = []
        this.dayWorkTime = 0
        this.addDayWorkTime = 0
        // console.log('选中的日期信息',e);
        
        // 遍历当月的数据找到当前选中的 那一天的全部的打卡数据
        // console.log('this.attendanceList',this.attendanceList);
        for(let i = 0; i < this.attendanceList.length; i++){
          let item = this.attendanceList[i]
          // 判断是否等于选中的日期
          if (item.attendanceDate === e.date){
            //如果找到选中那一天 那么item.attendanceJson就是当天的打卡json数据
            let myjson = item.attendanceJson.replace(/\\/g, '');//打卡修改
            // 此时已经拿到了选中那一天的所有的打卡数据了
            allClockinList = JSON.parse(myjson)
            // console.log('在日历上选中日期',item);
            if(item.attendanceWorkTime == null){
              this.dayWorkTime = 0
              this.addDayWorkTime = 0
            }else{
              this.dayWorkTime = parseFloat(item.attendanceWorkTime).toFixed(2)
            }
            
            if(this.dayWorkTime > 8){
              this.addDayWorkTime = (this.dayWorkTime - 8).toFixed(2)
            }
            break
          }
        }
        // console.log(allClockinList);
        // 如果上面的for遍历完this.allClockinList的长度还是为0那么就表示
        //今天没有打卡数据 那么清空显示的打卡数据
        // console.log('allClockinList.length == 0',allClockinList.length == 0);
        if(allClockinList.length == 0){
          this.clockinList = []
          return 
        }
        this.clockinList = []
        // console.log('for循环之前的打卡数组',this.clockinList);
        // 遍历当天的打卡数据 全部加到要渲染的打卡列表中
        // console.log('当天的打卡数据',allClockinList);
        for(let i = 0; i < allClockinList.length; i++){
          let item = allClockinList[i]
           let date = new Date(parseInt(item.showTime))
				   
          let hour = date.getHours()
          let myhour = hour < 10 ? '0' + hour : hour
          let month = date.getMinutes()
          let mymonth = month < 10 ? '0' + month : month
          let esc = date.getSeconds()
          let myesc = esc < 10 ? '0' + esc : esc
          let time = myhour + ':' + mymonth + ':' + myesc
          this.clockinList.push({
            status: 2,
            workStatus: item.isIn ? 0 : 1, //true就是 0 上班 false就是 1 下班
            time: time,
            address: item.projectName,
            part: '考勤附件',
            image: item.filePath
          })
          // console.log(this.clockinList);
        }
        
        console.log('此时已经添加完成了',this.clockinList);
        
        // 处理当天打卡次数为零的情况
        if(this.clockinList.length == 0){
          // 如果当天的打卡数量为0 那就直接return 下面的代码也没有用了
          return
        }
        // 处理当天打卡次数为1的情况
        // if(this.clockinList.length == 1){
        //   // 如果当天只打了一次卡那么就直接给他单独赋值就好了
        //   this.clockinList[0].status = 0
        //   // 而且一次打卡也没有必要计算 当天的工作时间 所以也是return
        //   return 
        // }
        // console.log('处理之前',this.clockinList);
        // 将当天的打卡根据上下班分成两个数组 并且按照时间排序
        // let upWork = []
        // let downWork = []
        // this.clockinList.forEach(item => {
        //   if(item.workStatus == 0)
        //     upWork.push(item)
        //   else
        //     downWork.push(item)
        // })
        // upWork = [
        //   {time: '7:09:07'},
        //   {time: '9:09:08'},
        //   {time: '10:09:37'},
        // ]
        // downWork = [
        //   {time: '14:09:35'},
        //   {time: '16:09:36'},
        //   {time: '17:09:05'}, 
        // ]
        
        // 排序
        // upWork.sort((a, b) => {
        //   return this.parseTime(a.time) - this.parseTime(b.time);
        // });
        // downWork.sort((a, b) => {
        //   return this.parseTime(a.time) - this.parseTime(b.time);
        // });
        // 需要保证两个数组的长度是一致的 如果不一致就是往里面push
        // 用更长的数组长度来遍历
        // let maxLen = upWork.length > downWork.length ? upWork.length : downWork.length 
        // console.log('maxLen',maxLen);
        // console.log('upWork 算法前',upWork, upWork.length);
        // console.log('downWork 算法前',downWork, downWork.length);
        // 然后同时遍历两个数组 上班下标是i 下班是j 
        // 我们要求i的时间必须小于j  并且j的时间必须小于i + 1
        // 如果i的时间大于j 那就说明当前的上班时间是错的 在i的前面插入一个null
        // 如果i的时间小于j了  但是j的时间大于i + 1 就说明下班的时间是错的 在下班的时间j前面插入一个null
          // for(let i = 0; i < maxLen; i++){
          //   // console.log('------------------------');
          //   if(upWork[i] == null || downWork[i] == null){
          //     break
          //   }
          //   // console.log('upWork[i].time',upWork[i].time);
          //   let upTime = this.parseTime(upWork[i].time)
          //   // console.log('downWork[j].time',downWork[j].time);
          //   let doTime = this.parseTime(downWork[i].time)
            
            
          //   // 如果i的时间大于j 那就说明当前的上班时间是错的 在i的前面插入一个null
          //   // console.log('upTime > doTime',upTime > doTime);
          //   if(upTime > doTime){
          //     upWork.splice(i, 0, {
          //           status: 0 , // 2正常 1黄色警告 0红色无记录
          //           workStatus: 0, // 0上班打卡 1下班打卡
          //           time: '无记录', //单次打卡时间
          //           address: '无记录', //打卡地点  
          //           part: '考勤附件',
          //           image: '/static/images/avatar.jpg' // 照片
          //     })
              
          //     continue
          //   }

          //   // 如果i的时间大于j 并且i+1没有时间了 那么j的时间一定是正确的 直接下一轮循环
          //   // console.log('i, j',i,j);
          //   // console.log('upWork[i + 1] == null',upWork[i + 1] == null);
            
            
          //   if(upWork[i + 1] == null){
          //     break
          //   }
          //   let upTimeAdd = this.parseTime(upWork[i + 1].time)
          //   // 如果i的时间小于j了  但是j的时间大于i + 1 就说明下班的时间是错的 在下班的时间j前面插入一个null
          //   // console.log('upTime',upTime);
          //   // console.log('doTime',doTime);
          //   // console.log('upTime < doTime && doTime > upTimeAdd',upTime < doTime && doTime > upTimeAdd);
          //   if(upTime < doTime && doTime > upTimeAdd){
          //     downWork.splice(i, 0, {
          //       status: 0 , // 2正常 1黄色警告 0红色无记录
          //       workStatus: 0, // 0上班打卡 1下班打卡
          //       time: '无记录', //单次打卡时间
          //       address: '无记录', //打卡地点  
          //       part: '考勤附件',
          //       image: '/static/images/avatar.jpg' // 照片
          //     })
              
          //     continue
          //   }
          //   maxLen = upWork.length > downWork.length ? upWork.length : downWork.length 
          //   // console.log('--------------------------------');
          // }
          
        // 统一长度 将null 付一个无考勤的对象占位
        // let newmaxLen = upWork.length > downWork.length ? upWork.length : downWork.length 
        // for(let i = 0; i < newmaxLen; i++){
        //   if(upWork[i] == null){
        //     upWork.push({
        //           status: 0 , // 2正常 1黄色警告 0红色无记录
        //           workStatus: 0, // 0上班打卡 1下班打卡
        //           time: '无记录', //单次打卡时间
        //           address: '无记录', //打卡地点  
        //           part: '考勤附件',
        //           image: '/static/images/avatar.jpg' // 照片
        //     })
        //   }else if(downWork[i] == null){
        //     downWork.push({
        //           status: 0 , // 2正常 1黄色警告 0红色无记录
        //           workStatus: 0, // 0上班打卡 1下班打卡
        //           time: '无记录', //单次打卡时间
        //           address: '无记录', //打卡地点  
        //           part: '考勤附件',
        //           image: '/static/images/avatar.jpg' // 照片
        //     })
        //   }
        // }
        // console.log('upWork 算法后',upWork, upWork.length);
        // console.log('downWork 算法后',downWork, downWork.length);
        
        // console.log('将上下班打卡数据合并成一个');
        // let mylist = []
        // for(let i = 0; i < upWork.length; i++){
        //   mylist.push(upWork[i])
        //   mylist.push(downWork[i])
        // }
        // console.log('将上下班打卡数据合并成一个', mylist);
        
        // this.judgeListStatus(mylist)
        this.clockinList = mylist
        return mylist
        // console.log(this.clockinList);
      },
        
      // 返回打卡数组中小的的状态值 也就是最严重的值
      isStatus(list){
        if(list.length == 0)
          return 3 //3 就是啥也不显示
        let minStatus = 99
        list.forEach(item => {
          if(item.status < minStatus)
            minStatus = item.status
        })
        return minStatus
      },
      
      // 遍历当月的有打卡的每一天 根据当天的打卡状态修改日历上的颜色
      changeCalendar(time){
        // console.log('changeCalendar',time);
        let todayList = this.onclickTime({date: time})
        this.clockinList = []
        // console.log('计算每组打卡的状态',this.isStatus(todayList));
        return this.isStatus(todayList)
      },
      
      //计算每组打卡的状态
      judgeListStatus(list){
        // 假设data是包含对象的数组
        let yourArray = list
        // 假设 yourArray 是包含对象的数组
        for (let i = 0; i < yourArray.length - 1; i += 2) {
          const currentTime = this.parseTime(yourArray[i].time);
          const nextTime = this.parseTime(yourArray[i + 1].time);
          const timeDifference = Math.abs(nextTime - currentTime) / 3600; // 计算时间差（小时）
        
          if (timeDifference < 2) {
            yourArray[i].status = 1;
            yourArray[i + 1].status = 1;
          }
        }
        // console.log('计算每组打卡的状态',yourArray);
      },
      
      // 将时分秒转成时间来比较大小
      parseTime(timeStr) {
        const parts = timeStr.split(':');
        if (parts.length === 3) {
          const hours = parseInt(parts[0], 10);
          const minutes = parseInt(parts[1], 10);
          const seconds = parseInt(parts[2], 10);
          return hours * 3600 + minutes * 60 + seconds;
        }
        return NaN; // Invalid time string
      },
      
      
      //根据年月来获取考勤数据 比如 '2023-09' 不给就默认查31个
      getattendanceList(nowTime = '', CardId = null){
        console.log('获取考勤数据携带的参数',nowTime,CardId);
        uni.$post(this.path + '/attendance/query',{
              attendanceDate: nowTime,
              attendanceName: '',
              permissionFlag: '',
              personCard: CardId || uni.getStorageSync('userCode'),
              attendanceStatus: 3, //这个是指定查询的考勤状态 这里的状态写死 每次查不管什么状态的考勤都查出来
              relativeProjectName: '',
          }).then(res => {
            if(res.code == 200){
              // console.log('/attendance/query请求的返回值数据',res);
              this.attendanceList = res.data.records
              // 这里面是这一个的考勤记录 里面每一个对象都是某天的数据
              // console.log('拿到的当月的原始数据',this.attendanceList);
              // let jsonToList = JSON.parse(this.attendanceList.attendanceJson)
              this.personCount = 0
              this.attendanceList.forEach(item =>{
                // let Mystatus = this.changeCalendar(item.attendanceDate)
                let Mystatus = item.attendanceStatus
                if(Mystatus == 0){
                  this.personCount += 1
                }
                this.timeAndsta.push({
                  attendanceDate: item.attendanceDate ,//考勤日期
                  attendanceStatus:  Mystatus// 考勤状态(0表示无考勤 1表示无效考勤 2表示有效考勤其他表示全部)
                })
              })
              // 赋值给日历对象 渲染状态
              this.markDays = this.timeAndsta
              this.onclickTime({date: this.getFormattedDate()})
            }else{
              uni.showToast({
                title: '考勤获取失败,请稍候重试',
                icon: 'error'
              })
            }
        
          })
        
      },
      //返回今天的日期 格式为2023-10-20
      getFormattedDate() {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0'); // Month is 0-based
        const day = String(today.getDate()).padStart(2, '0');
        
        const formattedDate = `${year}-${month}-${day}`;
        return formattedDate;
      },
      
      //获取当月的数据
      getNowMonthData(){
        //页面数据之后 遍历当月的考勤数据然后赋值
        this.totalWorkTime = 0
        this.validWork = 0
        this.invalidWork = 0
        this.nullWrok = 0
        let totalWorkTimeTamp = 0 //累计时长
        let validWorkTamp = 0//有效考勤
        let invalidWorkTamp = 0//无效考勤
        let nullWorkTamp = 0//无考勤
        this.attendanceList.forEach(item => {
          totalWorkTimeTamp += this.convertTimeToHours(item.attendanceWorkTime)//累计时长
          if(item.attendanceStatus == 2){//有效考勤
            validWorkTamp += 1
          }
          if(item.attendanceStatus == 1){//无效考勤
            invalidWorkTamp += 1
          }
        })
        // 当月目前的天数 减去 有效和无效考勤 就是无考勤
        nullWorkTamp = this.days - validWorkTamp - invalidWorkTamp
        
        this.totalWorkTime = totalWorkTimeTamp
        this.validWork = validWorkTamp
        this.invalidWork = invalidWorkTamp
        this.nullWrok = nullWorkTamp
      },
      
      //传递日期字符串 返回当月的天数
      getDaysInMonth(dateString){
        const validDateString = dateString.replace(/-00$/, '-01');
          // 将日期字符串转换为Date对象
          const date = new Date(dateString);
          // 获取月份的最后一天
          const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
        
          // 获取最后一天的日期，即月份的总天数
          const totalDays = lastDay.getDate();
          return totalDays;
      },
      
      formatNum(num) {
        let res = Number(num);
        return res < 10 ? '0' + res : res;
      },
    
      getToday() {
        let date = new Date();
        let y = date.getFullYear();
        let m = date.getMonth();
        let d = date.getDate();
        let week = new Date().getDay();
        let weekText = ['日', '一', '二', '三', '四', '五', '六'];
        let formatWeek = '星期' + weekText[week];
        let today = {
          date: y + '-' + this.formatNum(m + 1) + '-' + this.formatNum(d),
          week: formatWeek
        };
        return today;
      },
      
      
      // 获取当前月份数据
      monthDay(y, month) {
        let dates = [];
        let m = Number(month);
        let firstDayOfMonth = new Date(y, m - 1, 1).getDay(); // 当月第一天星期几
        let lastDateOfMonth = new Date(y, m, 0).getDate(); // 当月最后一天
        let lastDayOfLastMonth = new Date(y, m - 2, 0).getDate(); // 上一月的最后一天
        let weekstart = this.weekstart == 7 ? 0 : this.weekstart;
        let startDay = (() => {
          // 周初有几天是上个月的
          if (firstDayOfMonth == weekstart) {
            return 0;
          } else if (firstDayOfMonth > weekstart) {
            return firstDayOfMonth - weekstart;
          } else {
            return 7 - weekstart + firstDayOfMonth;
          }
        })();
        let endDay = 7 - ((startDay + lastDateOfMonth) % 7); // 结束还有几天是下个月的
        for (let i = 1; i <= startDay; i++) {
          dates.push({
            date: this.formatNum(lastDayOfLastMonth - startDay + i),
            day: weekstart + i - 1 || 7,
            month: m - 1 >= 0 ? this.formatNum(m - 1) : 12,
            year: m - 1 >= 0 ? y : y - 1
          });
        }
        for (let j = 1; j <= lastDateOfMonth; j++) {
          dates.push({
            date: this.formatNum(j),
            day: (j % 7) + firstDayOfMonth - 1 || 7,
            month: this.formatNum(m),
            year: y,
            isCurM: true //是否当前月份
          });
        }
        for (let k = 1; k <= endDay; k++) {
          dates.push({
            date: this.formatNum(k),
            day: (lastDateOfMonth + startDay + weekstart + k - 1) % 7 || 7,
            month: m + 1 <= 11 ? this.formatNum(m + 1) : 0,
            year: m + 1 <= 11 ? y : y + 1
          });
        }
        // console.log(dates);
        dates.forEach(item => {
          let time = item.year + '-' + item.month + '-' + item.date
          this.markDays.forEach(item2 => {
            if(time == item2.attendanceDate){
              item.status = item2.attendanceStatus
            }
          })
        })
        return dates;
      },
      
      
      isWorkDay(y, m, d) {
        //是否工作日
        let ymd = `${y}/${m}/${d}`;
        let formatDY = new Date(ymd.replace(/-/g, '/'));
        let week = formatDY.getDay();
        if (week == 0 || week == 6) {
          return false;
        } else {
          return true;
        }
      },
     
      isFutureDay(y, m, d) {
        //是否未来日期
        let ymd = `${y}/${m}/${d}`;
        let formatDY = new Date(ymd.replace(/-/g, '/'));
        let showTime = formatDY.getTime();
        let curTime = new Date().getTime();
        if (showTime > curTime) {
          return true;
        } else {
          return false;
        }
      },
      // 标记日期
      isMarkDay(y, m, d) {
        // console.log(y, m, d, '当前遍历的日期项', y - m - d);
        let flag = false;
        // console.log('传递过来需要标记的日期项', this.markDays);
        this.markDays.forEach(item => {
          let dy = `${y}-${m}-${d}`
          if (item == dy) {
            flag = true
          }
        })
        return flag;
      },
 
      isToday(y, m, d) {
        let checkD = y + '-' + m + '-' + d;
        let today = this.getToday().date;
        if (checkD == today) {
          return true;
        } else {
          return false;
        }
      },
      // 展开收起
      toggle() {
        this.monthOpen = !this.monthOpen;
        if (this.monthOpen) {
          this.positionTop = 0;
          // console.log('this.positionTop',this.positionTop);
          this.$emit('changeStatus', this.monthOpen)
          // console.log('this.monthOpen',this.monthOpen);
        } else {
          this.$emit('changeStatus', this.monthOpen)
          // console.log('this.monthOpen',this.monthOpen);
          let index = -1;
        
          this.dates.forEach((i, x) => {
            this.isToday(i.year, i.month, i.date) && (index = x);
          });
          this.positionTop = -((Math.ceil((index + 1) / 7) || 1) - 1) * 80;
          // console.log('this.positionTop',this.positionTop);
        }
      },
      // 点击回调
      selectOne(i, event) {
        let date = `${i.year}-${i.month}-${i.date}`;
        let selectD = new Date(date).getTime();
        let curTime = new Date().getTime();
        let week = new Date(date).getDay();
        let weekText = ['日', '一', '二', '三', '四', '五', '六'];
        let formatWeek = '星期' + weekText[week];
        let response = {
          date: date,
          week: formatWeek
        };
        if (!i.isCurM) {
          // console.log('不在当前月范围内');
          return false;
        }
        if (false) { // 改成false 表示不做判断  正常为selectD > curTime
          if (this.disabledAfter) {
            console.log('未来日期不可选');
            uni.showToast({
              title: '未来日期不可选中',
              icon: 'none',
              duration: 500
            })
            this.$refs.uToast.show({
                      title: '未来日期不可选中',
                      type: 'error',
                      position:'top',
                      icon:false
                    })
            return false;
          } else {
            this.choose = date;
            // this.$emit('onDayClick', response);
            this.onclickTime(response)
          }
        } else {
          this.choose = date;
          // this.$emit('onDayClick', response);
          this.onclickTime(response)
        }
        this.$emit('selectDate',response)
        
      },
      //改变年月
      changYearMonth(y, m) {
        this.dates = this.monthDay(y, m);
        this.y = y;
        this.m = m;
      },
      
      changeMonth(type) {
        if (type == 'pre') {
          // this.$emit('toogleMonth', {y: this.y, m: this.m - 1,type: 'sub'})
          this.clickMonth({y: this.y, m: this.m - 1,type: 'sub'})
          if (this.m + 1 == 2) {
            this.m = 12;
            this.y = this.y - 1;
          } else {
            this.m = this.m - 1;
          }
        } else {
          // this.$emit('toogleMonth', {y: this.y, m: this.m + 1,type: 'add'})
          this.clickMonth({y: this.y, m: this.m + 1,type: 'add'})
          if (this.m + 1 == 13) {
            this.m = 1;
            this.y = this.y + 1;
          } else {
            this.m = this.m + 1;
          }
        }
        this.dates = this.monthDay(this.y, this.m);
      }
          
    },

    beforeUpdate() {
      this.getNowMonthData()
    },
 
    onLoad(options) {
      console.log('options',options);
      this.isShowButton = options.status == 1 ? false : true 
      if(options.card != null){
         this.idCode = options.card
      }
      this.datetime = options.datetime
      this.nowYear = options.time.split('-')[0]
      this.nowMonth = parseInt(options.time.split('-')[1])
      this.changYearMonth(parseInt(options.time.split('-')[0]),parseInt(options.time.split('-')[1]))
      
      if(this.idCode.length !== 0){
        console.log('从有idcode进入',this.idCode);
        this.getattendanceList(this.datetime,this.idCode)
      }else{
        console.log('从没有idcode进入');
        this.getattendanceList(this.datetime)
      }
      
      this.dates = this.monthDay(this.y, this.m);
      // this.getattendanceList(options.datetime)
      !this.open && this.toggle();
      
    },
    created() {

    },

    mounted() {
      this.choose = this.getToday().date;
      this.dates = this.monthDay(this.y, this.m);
    },
    beforeMount() {
      this.getNowMonthData()
    },
    beforeUpdate() {
      this.getNowMonthData()
    },
  }
</script>

<style lang="scss">
  
  .notTrueblue{
    color: #055dfe !important;
  }
  .notTruered{
    color: #ec2626 !important;
  }
  .my-butbox{
    padding: 50rpx 0;
    .my-but{
      width: calc(100% - 50rpx);
      background-color: #007aff;
    }
  }
  
  .list{
    .item{
      background-color: #fff;
      padding: 10rpx;
      margin: 30rpx 20rpx;
      border-radius: 20rpx;
      font-size: 34rpx;
      .item-head{
        padding-left: 20rpx;
        .item-head-left{
          display: flex;
          align-items: center;
          color: #7f91ab;
        }
        .item-head-right{
          color: #bdbdbd;
        }
        display: flex;
        align-items: center;
        padding: 20rpx;
        justify-content: space-between;
      }
      .item-bot{
        margin-left: 80rpx;
        padding-bottom: 20rpx;
        font-size: 30rpx;
        color: #bdbdbd;
      }
    }
  }
  
  .error{
    color: #ec2626 !important;
    background-color: #ec2626 !important;
  }
  
  .errornotback{
    color: #ec2626 !important;
    border: 1px solid  #ec2626 !important;
  }
  
  .warn{
    color: #ee9818 !important;
    background-color: #ee9818 !important;
  }
  .warnnotback{
    color: #ee9818 !important;
    border: 1px solid #ee9818 !important;
  }
  
  .clockin-list{
    margin-top: 30rpx;
    background-color: #fff;
    padding-bottom: 50rpx;
    .clockin-item{
      .item-head{
        display: flex;
        align-items: center;
        padding: 0 20rpx ;
        .item-head-status{
          width: 150rpx;
          text-align: center;
          border: 1px solid #055dfe;
          color: #055dfe;
          border-radius: 50rpx;
        }
      }
      .item-middle{
        padding: 30rpx;
        padding-left: 60rpx;
        .item-middle-row{
          padding: 10rpx;
        }
      }
      .item-img{
        margin-left: 50rpx;
        width: 150rpx;
        height: 150rpx;
        border-radius: 30rpx;
        overflow: hidden;
        image{
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  
  
  .statistics-box{
    padding: 20rpx;
    background-color: #fff;
    .title-head{
      padding-bottom: 20rpx;
      display: flex;
      justify-content: space-between;
    }
    .head-chose{
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      background-color: #f2f2f2;
      .today{
        border-radius: 5rpx;
        height: 70rpx;
        line-height: 70rpx;
        width: 100rpx;
        text-align: center;
        background-color: #f2f2f2;
        color: #b4b4b4;
      }
    }
  }
 
  
  .calendar-tip{
    padding: 20rpx 0;
    display: flex;
    padding-left: 20rpx;
    align-items: center;
    .red-style{
      width: 15rpx;
      height: 15rpx;
      border-radius: 50%;
      background-color: #055dfe;
    }
    .red-bule{
      width: 15rpx;
      height: 15rpx;
      border-radius: 50%;
      background-color: red;
    }
  }

  
  .statistics-detail{
    margin-top: 30rpx;
    padding: 20rpx;
    background-color: #fff;
    border-bottom: 1px solid #e2e2e2;
    height: fit-content;
    .head{
      display: flex;
      align-items: center;
      padding: 30rpx 0;
      view{
        padding-left: 10rpx;
        font-weight: 500;
      }
    }
  }
  
  .statistics-box{
    margin-top: 30rpx;
    padding: 20rpx;
    background-color: #fff;
    border-bottom: 1px solid #e2e2e2;
    .head{
      display: flex;
      align-items: center;
      padding: 30rpx 0;
      view{
        padding-left: 10rpx;
        font-weight: 500;
      }
    }
  }
  .time-box{
    display: flex;
    justify-content: space-around;
    .time-left{
      padding: 25rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #055dfe;
      .workTime-left{font-size: 50rpx; font-weight: 500;}
    }
    .time-right{}
  }
  
  
  page{
    background-color: #f6f9fc;
  }
</style>

<style lang="scss" scoped>
	.calendar-wrapper {
		width: 100vw;
		color: #bbb7b7;
		font-size: 28rpx;
		text-align: center;
		background-color: #fff;
		padding-bottom: 10rpx;

		.header {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 88rpx;
			color: #42464A;
			font-size: 32rpx;
			font-weight: bold;
			border-bottom: 2rpx solid #f2f2f2;

			.pre,
			.next {
				color: #4d7df9;
				font-size: 28rpx;
				font-weight: normal;
				padding: 8rpx 15rpx;
				border-radius: 10rpx;
				border: 2rpx solid #dcdfe6;
			}

			.pre {
				margin-right: 30rpx;
			}

			.next {
				margin-left: 30rpx;
			}
		}

		.week {
			display: flex;
			align-items: center;
			height: 80rpx;
			line-height: 80rpx;
			border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);

			view {
				flex: 1;
			}
		}

		.content {
			position: relative;
			overflow: hidden;
			transition: height 0.4s ease;

			.days {
				transition: top 0.3s;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				position: relative;

				.item {
					position: relative;
					display: block;
					height: 80rpx;
					line-height: 80rpx;
					width: calc(100% / 7);

					.day {
						font-style: normal;
						display: inline-block;
						vertical-align: middle;
						width: 60rpx;
						height: 60rpx;
						line-height: 60rpx;
						overflow: hidden;
						border-radius: 60rpx;

						&.isMarkDay {
							background-color: green;
							color: #fff;
						}
            &.statusRed{
              background-color: #ec2626;
              color: #fff;
            }
            &.statusYellow{
              background-color: #ee9818;
              color: #fff;
            }
            &.statusGreen{
              background-color: #055dfe;
              color: #fff;
            }

						&.choose {
							background-color: #4d7df9;
							color: #fff;
						}

						&.nolm {
							color: #fff;
							opacity: 0.3;
						}
					}

					.isWorkDay {
						color: #42464a;
					}

					.notSigned {
						font-style: normal;
						width: 8rpx;
						height: 8rpx;
						background: #fa7268;
						border-radius: 10rpx;
						position: absolute;
						left: 50%;
						bottom: 0;
						pointer-events: none;
					}

					.today {
						color: #fff;
						background-color: #a8c0ff;
					}

					.workDay {
						font-style: normal;
						width: 8rpx;
						height: 8rpx;
						background: #4d7df9;
						border-radius: 10rpx;
						position: absolute;
						left: 50%;
						bottom: 0;
						pointer-events: none;
					}

					.markDay {
						font-style: normal;
						width: 8rpx;
						height: 8rpx;
						background: red;
						border-radius: 10rpx;
						position: absolute;
						left: 50%;
						bottom: 0;
						pointer-events: none;
					}
				}
			}
		}

		.hide {
			height: 80rpx !important;
		}

		.weektoggle {
			width: 85rpx;
			height: 42rpx;
      padding-bottom: 20rpx;
			position: relative;
			bottom: -42rpx;

			&.down {
				transform: rotate(180deg);
				bottom: 0;
			}
		}
	}
</style>
